#include "LibrarySystem.h"
#include "Date.h"
#include <iostream>
#include <algorithm>
#include <string>

// 构造函数，初始化管理员账户
LibrarySystem::LibrarySystem() : admin("admin", "admin") {}

// 启动图书管理系统，显示主菜单并根据用户选择进行操作
void LibrarySystem::start()
{
    // system("clear");
    cout << "\t\t\t************欢迎登录图书管理系统************" << endl;
    cout << "\t\t\t1. 管理员登录" << endl;
    cout << "\t\t\t2. 读者登录" << endl;
    cout << "\t\t\t0. 退出系统" << endl;

    string choice = getValidInput("请选择: ", 0, 2);

    if (choice == "1")
    {
        adminLogin();
    }
    else if (choice == "2")
    {
        Reader *currentReader = nullptr;
        if (readerLogin(currentReader))
        {
            menuReader(*currentReader);
        }
    }
    else
    {
        cout << "系统退出" << endl;
        return;
    }
}

// 管理员登录界面，验证管理员密码最多三次
void LibrarySystem::adminLogin()
{
    // system("clear");
    cout << "---------- 管理员登录 ----------" << endl;
    int attempts = 0;
    string password;

    while (attempts < 3)
    {
        cout << "请输入密码: ";
        cin >> password;
        cin.ignore(); // 清除缓冲区

        if (password == admin.getPassword())
        {
            cout << "登录成功！" << endl;
            // system("pause");
            menuAdmin();
            return;
        }
        attempts++;
        cout << "密码错误，剩余尝试次数: " << (3 - attempts) << endl;
    }
    cout << "登录失败，超过最大尝试次数！" << endl;
    // system("pause");
    start();
}

// 读者登录界面，验证读者账号和密码最多三次
bool LibrarySystem::readerLogin(Reader *&reader)
{
    // system("clear");
    cout << "---------- 读者登录 ----------" << endl;
    int attempts = 0;
    string account, password;

    while (attempts < 3)
    {
        account = getNonEmptyString("请输入账号: ");
        password = getNonEmptyString("请输入密码: ");

        Reader *found = readerManager.findReader(account);
        if (found && found->getPassword() == password)
        {
            reader = found;
            cout << "登录成功！" << endl;
            // system("pause");
            return true;
        }
        attempts++;
        cout << "账号或密码错误，剩余尝试次数: " << (3 - attempts) << endl;
    }
    cout << "登录失败，超过最大尝试次数！" << endl;
    // system("pause");
    return false;
}

// 管理员菜单，提供图书管理和读者管理等功能
void LibrarySystem::menuAdmin()
{
    while (true)
    {
        // system("clear");
        cout << "\t\t\t************ 管理员菜单 ************" << endl;
        cout << "\t\t\t1. 图书管理" << endl;
        cout << "\t\t\t2. 读者管理" << endl;
        cout << "\t\t\t0. 返回主菜单" << endl;

        string choice = getValidInput("请选择: ", 0, 2);

        if (choice == "1")
        {
            menuBookManagement();
        }
        else if (choice == "2")
        {
            menuReaderManagement();
        }
        else
        {
            start();
            return;
        }
    }
}

// 图书管理菜单，提供添加、删除、修改、查询和显示所有图书的功能
void LibrarySystem::menuBookManagement()
{
    while (true)
    {
        // system("clear");
        cout << "\t\t\t********** 图书管理菜单 **********" << endl;
        cout << "\t\t\t1. 添加图书" << endl;
        cout << "\t\t\t2. 删除图书" << endl;
        cout << "\t\t\t3. 修改图书" << endl;
        cout << "\t\t\t4. 查询图书" << endl;
        cout << "\t\t\t5. 显示所有图书" << endl;
        cout << "\t\t\t0. 返回上一级" << endl;

        string choice = getValidInput("请选择: ", 0, 5);

        if (choice == "1")
        {
            string isbn = getNonEmptyString("请输入ISBN: ");
            string title = getNonEmptyString("请输入书名: ");
            string author = getNonEmptyString("请输入作者: ");
            int quantity = stoi(getNonEmptyString("请输入初始数量 "));
            bookManager.addBook(Book(isbn, title, author, quantity));
            cout << "图书添加成功！" << endl;
            // system("pause");
        }
        else if (choice == "2")
        {
            string isbn = getNonEmptyString("请输入要删除的ISBN: ");
            if (bookManager.deleteBook(isbn))
            {
                cout << "图书删除成功！" << endl;
            }
            else
            {
                cout << "未找到该图书！" << endl;
            }
            // system("pause");
        }
        else if (choice == "3")
        {
            string isbn = getNonEmptyString("请输入要修改的ISBN: ");
            Book *book = bookManager.findBook(isbn);
            if (book)
            {
                string newTitle = getNonEmptyString("请输入新书名: ");
                string newAuthor = getNonEmptyString("请输入新作者: ");
                bookManager.modifyBook(isbn, Book(isbn, newTitle, newAuthor));
                cout << "图书修改成功！" << endl;
            }
            else
            {
                cout << "未找到该图书！" << endl;
            }
            // system("pause");
        }
        else if (choice == "4")
        {
            string isbn = getNonEmptyString("请输入ISBN查询: ");
            Book *book = bookManager.findBook(isbn);
            if (book)
            {
                system("clear");
                cout << "ISBN: " << book->getIsbn() << endl;
                cout << "书名: " << book->getTitle() << endl;
                cout << "作者: " << book->getAuthor() << endl;
                cout << "状态: " << (book->isAvailableToBorrow() ? "可借" : "已借") << endl;
            }
            else
            {
                cout << "未找到该图书！" << endl;
            }
            // system("pause");
        }
        else if (choice == "5")
        {
            bookManager.displayBooks();
        }
        else
        {
            return;
        }
    }
}

// 读者管理菜单，提供添加、删除、修改密码、查询和显示所有读者的功能
void LibrarySystem::menuReaderManagement()
{
    while (true)
    {
        // system("clear");
        cout << "\t\t\t********** 读者管理菜单 **********" << endl;
        cout << "\t\t\t1. 添加读者" << endl;
        cout << "\t\t\t2. 删除读者" << endl;
        cout << "\t\t\t3. 修改读者密码" << endl;
        cout << "\t\t\t4. 查询读者" << endl;
        cout << "\t\t\t5. 显示所有读者" << endl;
        cout << "\t\t\t6. 帮助读者借书" << endl;
        cout << "\t\t\t7. 查看读者借阅记录" << endl;
        cout << "\t\t\t0. 返回上一级" << endl;

        string choice = getValidInput("请选择: ", 0, 7);

        if (choice == "1")
        {
            string account = getNonEmptyString("请输入读者账号: ");
            string password = getNonEmptyString("请输入读者密码: ");
            readerManager.addReader(Reader(account, password));
            cout << "读者添加成功！" << endl;
            // system("pause");
        }
        else if (choice == "2")
        {
            string account = getNonEmptyString("请输入要删除的账号: ");
            if (readerManager.deleteReader(account))
            {
                cout << "读者删除成功！" << endl;
            }
            else
            {
                cout << "未找到该读者！" << endl;
            }
            // system("pause");
        }
        else if (choice == "3")
        {
            string account = getNonEmptyString("请输入要修改的账号: ");
            string newPassword = getNonEmptyString("请输入新密码: ");
            if (readerManager.modifyReader(account, newPassword))
            {
                cout << "密码修改成功！" << endl;
            }
            else
            {
                cout << "未找到该读者！" << endl;
            }
            // system("pause");
        }
        else if (choice == "4")
        {
            string account = getNonEmptyString("请输入账号查询: ");
            Reader *reader = readerManager.findReader(account);
            if (reader)
            {
                // system("clear");
                cout << "账号: " << reader->getAccount() << endl;
                cout << "密码: " << reader->getPassword() << endl;
                cout << "借阅图书: " << (reader->borrowBooks.empty() ? "无" : "有") << endl;
            }
            else
            {
                cout << "未找到该读者！" << endl;
            }
            // system("pause");
        }
        else if (choice == "5")
        {
            readerManager.displayReaders();
        }
        else if (choice == "6")
        {
            helpReaderBorrowBook();
        }
        else if (choice == "7")
        {
            viewReaderBorrowRecords();
        }
        else
        {
            return;
        }
    }
}

// 读者功能菜单，提供借阅、归还、查看借阅记录、查询图书和显示所有图书的功能
void LibrarySystem::menuReader(Reader &currentReader)
{
    while (true)
    {
        // system("clear");
        cout << "\t\t\t********** 读者功能菜单 **********" << endl;
        cout << "\t\t\t1. 借阅图书" << endl;
        cout << "\t\t\t2. 归还图书" << endl;
        cout << "\t\t\t3. 查看借阅记录" << endl;
        cout << "\t\t\t4. 查询图书" << endl; // 新增功能：按ISBN查询图书
        cout << "\t\t\t5. 显示所有图书" << endl;
        cout << "\t\t\t0. 退出登录" << endl;

        string choice = getValidInput("请选择: ", 0, 5);

        if (choice == "1")
        {
            string isbn = getNonEmptyString("请输入要借阅的图书ISBN: ");
            Book *book = bookManager.findBook(isbn);
            time_t borrowTime, dueTime;

            if (book && book->isAvailableToBorrow())
            {
                Date borrowDate;
                Date dueDate = borrowDate.addDays(30);
                currentReader.borrowBooks.push_back({
                    isbn,
                    static_cast<time_t>(borrowDate.toTimeT()), // 转换为time_t
                    static_cast<time_t>(dueDate.toTimeT())     // 转换为time_t
                });
                book->setQuantity(book->getQuantity() - 1);
                // currentReader.borrowBooks.push_back(isbn, );
                cout << "借阅成功！" << endl;
                readerManager.saveToFile();
                bookManager.saveToFile();
            }
            else
            {
                cout << "图书不可借或不存在！" << endl;
            }
            // system("pause");
        }
        // else if (choice == "2")
        // {
        //     string isbn = getNonEmptyString("请输入要归还的图书ISBN: ");
        //     Book *book = bookManager.findBook(isbn);
        //     if (book)
        //     {
        //         auto it = find(currentReader.borrowedBooks.begin(),
        //                        currentReader.borrowedBooks.end(), isbn);
        //         if (it != currentReader.borrowedBooks.end())
        //         {
        //             //                    book->setAvailability(true);
        //             book->setQuantity(book->getQuantity() + 1);
        //             currentReader.borrowedBooks.pop_back();
        //             // 少了对读者信息的修改
        //             cout << "归还成功！" << endl;
        //             readerManager.saveToFile();
        //             bookManager.saveToFile();
        //         }
        //         else
        //         {
        //             cout << "你未借阅该图书！" << endl;
        //         }
        //     }
        //     else
        //     {
        //         cout << "图书不存在！" << endl;
        //     }
        //     // system("pause");
        // }

        else if (choice == "2")
        {
            string isbn = getNonEmptyString("请输入要归还的图书ISBN: ");
            Book *book = bookManager.findBook(isbn);

            if (book)
            {
                // 使用find_if查找匹配的借阅记录
                auto it = std::find_if(
                    currentReader.borrowBooks.begin(),
                    currentReader.borrowBooks.end(),
                    [&isbn](const Reader::BorrowBooks &record)
                    {
                        return record.isbn == isbn;
                    });

                if (it != currentReader.borrowBooks.end())
                {
                    // 添加逾期判断
                    Date currentDate;
                    if (currentDate.toTimeT() > it->dueTime)
                    {
                        cout << "逾期归还！应还日期为："
                             << Date(it->dueTime).toString("%Y-%m-%d") << endl;
                    }

                    // 更新图书库存
                    book->setQuantity(book->getQuantity() + 1);

                    // 删除借阅记录
                    currentReader.borrowBooks.erase(it);

                    cout << "归还成功！" << endl;
                    readerManager.saveToFile();
                    bookManager.saveToFile();
                }
                else
                {
                    cout << "你未借阅该图书！" << endl;
                }
            }
            else
            {
                cout << "图书不存在！" << endl;
            }
        }
        // else if (choice == "3")
        // {
        //     // system("clear");
        //     cout << "---------- 借阅记录 ----------" << endl;
        //     if (currentReader.borrowedBooks.empty())
        //     {
        //         cout << "没有借阅记录" << endl;
        //     }
        //     else
        //     {
        //         for (const auto &isbn : currentReader.borrowedBooks)
        //         {
        //             Book *book = bookManager.findBook(isbn);
        //             if (book)
        //             {
        //                 cout << "ISBN: " << book->getIsbn()
        //                      << "\t书名: " << book->getTitle() << endl;
        //             }
        //         }
        //     }
        //     // system("pause");
        // }

        else if (choice == "3")
        {
            system("clear");
            cout << "---------- 借阅记录 ----------" << endl;
            if (currentReader.borrowBooks.empty())
            {
                cout << "没有借阅记录" << endl;
            }
            else
            {
                for (const auto &record : currentReader.borrowBooks)
                {
                    Book *book = bookManager.findBook(record.isbn);
                    if (book)
                    {
                        cout << "ISBN: " << record.isbn << endl
                             << "书名: " << book->getTitle() << endl
                             << "借书日期: " << Date(record.borrowTime).toString() << endl
                             << "应还日期: " << Date(record.dueTime).toString() << endl
                             << "------------------------------" << endl;
                    }
                }
            }
            // system("pause");
        }

        else if (choice == "4")
        {
            // 新增：查询图书（按ISBN）
            string isbn = getNonEmptyString("请输入ISBN查询: ");
            Book *book = bookManager.findBook(isbn);
            if (book)
            {
                system("clear");
                cout << "ISBN: " << book->getIsbn() << endl;
                cout << "书名: " << book->getTitle() << endl;
                cout << "作者: " << book->getAuthor() << endl;
                cout << "状态: " << (book->isAvailableToBorrow() ? "可借" : "已借") << endl;
            }
        }
        else if (choice == "5")
        { // 新增：显示所有图书
            bookManager.displayBooks();
        }
        else
        {
            start();
            return;
        }
    }
}

// 管理员帮助读者借书
void LibrarySystem::helpReaderBorrowBook()
{
    string account = getNonEmptyString("请输入读者账号: ");
    Reader *reader = readerManager.findReader(account);

    if (!reader)
    {
        cout << "读者不存在！" << endl;
        return;
    }

    string isbn = getNonEmptyString("请输入要借阅的ISBN: ");
    Book *book = bookManager.findBook(isbn);

    if (book && book->isAvailableToBorrow())
    {
        Date borrowDate;
        Date dueDate = borrowDate.addDays(30);

        reader->borrowBooks.emplace_back(
            isbn,
            borrowDate.toTimeT(),
            dueDate.toTimeT());

        book->setQuantity(book->getQuantity() - 1);
        readerManager.saveToFile();
        bookManager.saveToFile();

        cout << "成功为读者 [" << account << "] 借阅《" << book->getTitle() << "》" << endl;
    }
    else
    {
        cout << "图书不可借或不存在！" << endl;
    }
}

// 查看读者借阅记录
void LibrarySystem::viewReaderBorrowRecords()
{
    string account = getNonEmptyString("请输入读者账号: ");
    Reader *reader = readerManager.findReader(account);

    if (!reader)
    {
        cout << "读者不存在！" << endl;
        return;
    }

    cout << "========= 读者 [" << account << "] 的借阅记录 =========" << endl;
    if (reader->borrowBooks.empty())
    {
        cout << "暂无借阅记录" << endl;
        return;
    }

    for (const auto &record : reader->borrowBooks)
    {
        Book *book = bookManager.findBook(record.isbn);
        cout << "ISBN: " << record.isbn << endl;
        cout << "书名: " << (book ? book->getTitle() : "未知图书") << endl;
        cout << "借书日期: " << Date(record.borrowTime).toString() << endl;
        cout << "应还日期: " << Date(record.dueTime).toString() << endl;
        cout << "----------------------------------------" << endl;
    }
}
// 获取用户输入的合法选项
string LibrarySystem::getValidInput(const string &prompt, int mmin, int mmax)
{
    string input;
    while (true)
    {
        cout << prompt; // 输入提示
        cin >> input;
        cin.ignore(); // 清除缓冲区
        if (input.size() == 1 && input[0] >= '0' && input[0] <= '9')
        {
            int num = stoi(input);
            if (num >= mmin && num <= mmax)
            {
                return input;
            }
        }
        cout << "输入错误，请重新输入（范围" << mmin << "-" << mmax << "）" << endl;
    }
}

// 获取用户输入的非空字符串
string LibrarySystem::getNonEmptyString(const string &prompt)
{
    string input;
    while (true)
    {
        cout << prompt;
        getline(cin, input);
        if (!input.empty())
        {
            return input;
        }
        cout << "输入不能为空，请重新输入" << endl;
    }
}
